<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { get, post, put, del } from '@/utils/request'
import { areaList as vantAreaList } from '@vant/area-data'
import axios from 'axios'
// 地址类型声明
interface Address {
  _id?: string
  name: string
  phone: string
  area: string
  address: string
  areaCode?: string
  isDefault?: boolean
}

const areaList = ref<any>(vantAreaList)
const loadingAddress = ref<boolean>(false)
const router = useRouter()
const addressList = ref<Address[]>([])
const selectedId = ref<string>('')
const userId = (localStorage.getItem('userId') || '') as string
const addressInfo = ref<Partial<Address & { addressDetail?: string; tel?: string }>>({})
const isAdd = ref<boolean>(false)
const currentLocation = ref<{ latitude: string; longitude: string }>({ latitude: '', longitude: '' })

// 获取数据
onMounted(async () => {
  // 1. 优先用本地缓存
  const localAddressList = localStorage.getItem('address')
  if (localAddressList) {
    const arr: Address[] = JSON.parse(localAddressList)
    if (Array.isArray(arr) && arr.length > 0) {
      addressList.value = arr

      const def = arr.find(a => a.isDefault)
      selectedId.value = def ? (def._id as string) : (arr[0]._id as string)
    }
  }
  // 2. 请求后端，拿到新数据后覆盖
  try {
    const res = await get('/LXL/getaddress', { userId })
    if (res.data) {
      addressList.value = res.data as Address[]
      const def = addressList.value.find(a => a.isDefault)
      selectedId.value = def ? (def._id as string) : (addressList.value[0]?._id as string)
    }
  } catch (e) { }

})
watch(addressList, (val) => {
  localStorage.setItem('address', JSON.stringify(val))
}, { deep: true })
// 选择地址
async function selectAddress(id: string) {
  selectedId.value = id
  addressList.value.forEach(item => {
    item.isDefault = (item._id === id)
  })
  await post('/LXL/setDefaultAddress', { userId, addressId: id })
}
function goBack() {
  router.push('/OrderConfirmed1')
}

const showAddDialog = ref<boolean>(false)
// 新增：初始化包含 tag、address、isDefault
const newAddress = ref<{ tag?: string; address: string; isDefault: boolean }>({ address: '', isDefault: false })

function openAddDialog() {
  showAddDialog.value = true
  addressInfo.value = {}
  isAdd.value = true
}
function closeAddDialog() {
  showAddDialog.value = false
  newAddress.value = { tag: '住宅', address: '', isDefault: false }
}


const deletingId = ref<string | null>(null)
function confirmDelete(id: string) {
  if (window.confirm('确定要删除该地址吗？')) {
    deleteAddress(id)
  }
}
async function deleteAddress(id: string) {
  // 判断被删的是不是当前选中（默认）地址
  const deletedIsDefault = addressList.value.find(a => a._id === id)?.isDefault
  loadingAddress.value = true
  await post('/LXL/deleteAddress', { addressId: id })

  // 重新拉取地址列表
  const res = await get('/LXL/getaddress', { userId })
  if (res.data && res.data.length > 0) {
    addressList.value = res.data as Address[]
    const def = addressList.value.find(a => a.isDefault)
    if (def) {
      selectedId.value = def._id as string
    } else {
      // 没有默认地址，自动选第一个并设为默认
      selectedId.value = addressList.value[0]._id as string
      await post('/LXL/setDefaultAddress', { userId, addressId: selectedId.value })
      // 再次刷新，确保状态同步
      const res2 = await get('/LXL/getaddress', { userId })
      addressList.value = res2.data as Address[]
    }
  } else {
    addressList.value = []
    selectedId.value = ''
  }
  loadingAddress.value = false
}

function goToPay() {
  router.push('/PayView')
}
const searchResult = ref<any[]>([])
async function onSave(detail: any) {
  loadingAddress.value = true
  showAddDialog.value = false
  const address: Address = {
    // 兼容编辑和新增模式下的不同字段名
    address: detail.detail || detail.addressDetail || detail.address || '',
    // isDefault: detail.isDefault, // 移除 isDefault 字段
    name: detail.name,
    phone: detail.tel,
    areaCode: detail.areaCode, // 关键
    area: detail.province + detail.city + detail.county, // 可选，便于展示
  }
  if (!isAdd.value) {
    // 更新
    address._id = selectedId.value
    await post('/LXL/updateAddress', { userId, address })
    // 直接更新本地数据，减少接口调用
    const index = addressList.value.findIndex(item => item._id === selectedId.value)
    if (index !== -1) {
      // 确保字段正确映射
      addressList.value[index] = {
        ...addressList.value[index],
        name: address.name,
        phone: address.phone,
        areaCode: address.areaCode,
        area: address.area,
        address: address.address, // 确保详细地址正确保存
        isDefault: address.isDefault
      }
    }
  } else {
    // 新增
    selectedId.value = ''
    addressInfo.value = {}
    const res = await post('/LXL/addAddress', { userId, ...address })
    if (res.data) {
      if (res.data.isDefault) {
        // 先清除本地所有默认
        addressList.value.forEach(item => item.isDefault = false)
      }
      addressList.value.push(res.data as Address)
    }
  }

  // 检查是否需要设置默认地址
  const hasDefault = addressList.value.some(item => item.isDefault)
  if (!hasDefault && addressList.value.length > 0) {
    // 没有默认地址，设置第一个为默认
    const firstId = addressList.value[0]._id as string
    await post('/LXL/setDefaultAddress', { userId, addressId: firstId })
    // 更新本地数据
    addressList.value.forEach(item => {
      item.isDefault = item._id === firstId
    })
    selectedId.value = firstId
  } else {
    // 有默认地址，选中默认地址
    const def = addressList.value.find(a => a.isDefault)
    selectedId.value = def ? (def._id as string) : (addressList.value[0]?._id as string) || ''
  }

  loadingAddress.value = false
}


async function onChangeDetail(detail: any) {
  newAddress.value.address = detail.detail
}

//回显
function openEditDialog(item: Address) {
  showAddDialog.value = true
  //
  const bd: Address[] = JSON.parse(localStorage.getItem('address') || '[]')
  const iii = bd.find(a => a._id === item._id)
  addressInfo.value = {
    name: iii?.name || '',
    tel: iii?.phone || '',
    areaCode: iii?.areaCode,
    addressDetail: iii?.address || '',
    isDefault: iii?.isDefault,
  }
  selectedId.value = item._id as string
  isAdd.value = false

}
async function getinfoD(): Promise<void> {
  navigator.geolocation.getCurrentPosition(async (pos) => {
    const { latitude, longitude } = pos.coords
    console.log('定位信息:', latitude, longitude);
    const res: any = await axios.get(`https://restapi.amap.com/v3/geocode/regeo?location=${longitude},${latitude}&key=a11f0cfcc581b99eb81e1a93a1ed4957&radius=1000&extensions=base`)
    console.log(res.data);
    let hui = res.data
     if (res.data.status === '1') {
      // 成功获取地址信息
      const streetNumber = hui.regeocode.addressComponent.streetNumber
      const street = streetNumber.street
      const number = streetNumber.number
      const adcode = hui.regeocode.addressComponent.adcode
      // 更新地址信息
      addressInfo.value = {
        ...addressInfo.value,
        areaCode: adcode,
        addressDetail: `街道：${street}, 门牌：${number}`,
      }
    }
   
  })
}

function copyAddress(item: Address) {
  // 复制完整的地址信息
  const text = `收货人：${item.name || ''}\n电话：${item.phone || ''}\n地址：${item.area || ''} ${item.address || ''}`
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(() => {
      alert('复制成功')
    }, () => {
      alert('复制失败，请手动复制')
    })
  } else {
    // 兼容旧浏览器
    const textarea = document.createElement('textarea')
    textarea.value = text
    document.body.appendChild(textarea)
    textarea.select()
    try {
      document.execCommand('copy')
      alert('复制成功')
    } catch (err) {
      alert('复制失败，请手动复制')
    }
    document.body.removeChild(textarea)
  }
}

// 新增 onCancel 方法，关闭弹窗
function onCancel(): void {
  closeAddDialog()
}
</script>

<template>
    <div class="edit-address">
        <div class="header">
            <span class="back" @click="goBack">←</span>
            <span class="title">送货地址</span>
        </div>
        <div class="address-list">
            <div v-if="loadingAddress" class="address-loading">
                <div class="order-loading">
                    <span class="loader"></span>
                    <span style="margin-top:12px;">加载中...</span>
                </div>
            </div>
            <template v-else>
                <div class="address-card" v-for="item in addressList" :key="item._id"
                    :class="{ selected: item.isDefault }">
                    <div class="address-radio">
                        <span v-if="item.isDefault" class="radio checked"></span>
                        <span v-else class="radio"></span>
                    </div>

                    <div class="address-info" @click="selectAddress(item._id)">
                        <div class="address-type">
                            <div class="contact-info">{{ item.name }} {{ item.phone }}</div>
                            <div class="address-detail">{{ item.area }} {{ item.address }}</div>
                            <span v-if="item.isDefault" class="default">(默认地址)</span>
                        </div>
                    </div>
                    <div class="address-actions">

                        <button class="edit-btn" @click.stop="openEditDialog(item)">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                                <path d="M3 17.25V21h3.75l11.06-11.06-3.75-3.75L3 17.25z" fill="#111" />
                                <path
                                    d="M20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
                                    fill="#111" />
                            </svg>
                        </button>
                        <button class="copy-btn" @click.stop="copyAddress(item)">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                                <rect x="7" y="7" width="10" height="14" rx="2" stroke="#111" stroke-width="1.5" />
                                <rect x="3" y="3" width="10" height="14" rx="2" stroke="#bdbdbd" stroke-width="1.5" />
                            </svg>
                        </button>
                        <button class="delete-btn" @click.stop="confirmDelete(item._id)">
                            <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
                                <rect x="5" y="6" width="14" height="14" rx="2" stroke="#e74c3c" stroke-width="1.5" />
                                <path d="M7 6V4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2" stroke="#e74c3c" stroke-width="1.5" />
                                <path d="M10 11v4M14 11v4" stroke="#e74c3c" stroke-width="1.5" stroke-linecap="round" />
                            </svg>
                        </button>
                    </div>

                </div>
                <button class="add-btn" @click="openAddDialog">添加新地址</button>
            </template>

        </div>

        <div v-if="showAddDialog" class="add-dialog-mask" @click.self="closeAddDialog">
            <div class="add-dialog">
                <button @click="getinfoD">定位</button>
                <van-address-edit :area-list="areaList" :address-info="addressInfo" show-postal show-delete
                    show-search-result :search-result="searchResult" @save="onSave" @delete="onCancel"
                    @change-detail="onChangeDetail" switch-active-color="#111" delete-button-text="取消" />
            </div>
        </div>
        <div class="footer">
            <button class="confirm-btn" @click="goToPay">确定</button>
        </div>
    </div>

</template>

<style scoped>
.edit-address {
    background: #fff;
    min-height: 100vh;
    font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

.header {
    display: flex;
    align-items: center;
    height: 56px;
    padding: 0 0 0 12px;
    font-size: 20px;
    font-weight: bold;
    position: relative;
    background: #fff;
}

.back {
    font-size: 24px;
    margin-right: 8px;
    cursor: pointer;
}

.title {
    flex: 1;
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    margin-right: 32px;
}

.address-list {
    margin: 24px 0 0 0;
}

.address-card {
    position: relative;
    display: flex;
    align-items: center;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
    border-radius: 24px;
    padding: 16px 20px;
    margin: 0 16px 24px 16px;
    cursor: pointer;
    border: 2px solid transparent;
    transition: border 0.2s;
}

.address-card.selected {
    border: 2px solid #111;
    background: #f7f7f7;
}

.address-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: #f2f2f2;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
}

.address-info {
    flex: 1;
    min-width: 0;
}

.address-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 0px 8px;
}

.address-type {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 4px;
}

.contact-info {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 4px;
    color: #222;
}

.address-detail {
    font-size: 14px;
    color: #666;
    line-height: 1.4;
}

.default {
    color: #111;
    font-size: 14px;
    margin-left: 4px;
    font-weight: bold;
}

.address-radio {
    margin: 0px 8px;
    display: flex;
    align-items: center;
}

.radio {
    width: 24px;
    height: 24px;
    border: 2px solid #bdbdbd;
    border-radius: 50%;
    display: inline-block;
    background: #fff;
    position: relative;
}

.radio.checked {
    border: 2px solid #111;
}

.radio.checked::after {
    content: '';
    display: block;
    width: 12px;
    height: 12px;
    background: #111;
    border-radius: 50%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.add-btn {
    width: 90vw;
    max-width: 500px;
    height: 48px;
    background: #f2f2f2;
    color: #222;
    font-size: 18px;
    font-weight: bold;
    border: none;
    border-radius: 24px;
    margin: 24px auto 0 auto;
    display: block;
    letter-spacing: 2px;
    cursor: pointer;
}

.footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: transparent;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80px;
    z-index: 10;
}

.confirm-btn {
    width: 90vw;
    max-width: 500px;
    height: 56px;
    background: #111;
    color: #fff;
    font-size: 20px;
    font-weight: bold;
    border: none;
    border-radius: 28px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    cursor: pointer;
    letter-spacing: 2px;
}

.add-dialog-mask {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.22);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    backdrop-filter: blur(1.5px);
    -webkit-backdrop-filter: blur(1.5px);
    /* Safari 9+ 兼容 */
}

.add-dialog {
    background: #fff;
    border-radius: 20px;
    padding: 32px 28px 20px 28px;
    min-width: 320px;
    max-width: 90vw;
    box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.18), 0 1.5px 6px 0 rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    align-items: stretch;
    animation: popIn .25s cubic-bezier(.4, 2, .6, 1) both;
}

@keyframes popIn {
    0% {
        transform: scale(0.95);
        opacity: 0;
    }

    100% {
        transform: scale(1);
        opacity: 1;
    }
}

.add-dialog-title {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 22px;
    text-align: center;
    color: #222;
    letter-spacing: 1px;
}

.add-dialog-select,
.add-dialog-input {
    border: 1.5px solid #e5e5e5;
    border-radius: 10px;
    padding: 12px 14px;
    font-size: 16px;
    margin-bottom: 18px;
    outline: none;
    transition: border 0.2s;
    background: #fafbfc;
}

.add-dialog-select:focus,
.add-dialog-input:focus {
    border: 1.5px solid #111;
    background: #fff;
}

.add-dialog-checkbox {
    display: flex;
    align-items: center;
    font-size: 15px;
    margin-bottom: 22px;
    gap: 8px;
    color: #222;
    user-select: none;
}

.add-dialog-checkbox input[type=\"checkbox\"] {
    width: 18px;
    height: 18px;
    accent-color: #111;
    border-radius: 4px;
}

.add-dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    margin-top: 6px;
}

.add-dialog-actions button {
    padding: 10px 28px;
    border: none;
    border-radius: 10px;
    font-size: 16px;
    background: #f2f2f2;
    color: #222;
    cursor: pointer;
    font-weight: 500;
    transition: background 0.2s, color 0.2s;
}

.add-dialog-actions button:last-child {
    background: #111;
    color: #fff;
    font-weight: 700;
}

.add-dialog-mask {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.22);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    backdrop-filter: blur(1.5px);
    -webkit-backdrop-filter: blur(1.5px);
    /* Safari 9+ 兼容 */
}

.delete-btn {
    background: none;
    border: none;
    padding: 0 2px;
    cursor: pointer;
    display: flex;
    align-items: center;
    height: 36px;
    width: 36px;
    border-radius: 50%;
    transition: background 0.2s;
}

.delete-btn:active {
    background: #fbeaea;
}

.delete-btn svg {
    display: block;
}

.address-loading {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 120px;
}

.spinner {
    width: 32px;
    height: 32px;
    border: 4px solid #eee;
    border-top: 4px solid #111;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.order-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 120px;
    color: #bdbdbd;
    font-size: 18px;
}

.loader {
    width: 36px;
    height: 36px;
    border: 4px solid #eee;
    border-top: 4px solid #111;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 8px;
}

.add-dialog {
    width: 90vw;
    max-width: 400px;
    min-width: unset;
    box-sizing: border-box;
    background: #fff;
    border-radius: 20px;
    padding: 24px 16px 16px 16px;
    box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.18), 0 1.5px 6px 0 rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    align-items: stretch;
}

.add-dialog-title {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 18px;
    text-align: center;
    color: #222;
    letter-spacing: 1px;
}

.add-dialog-row {
    margin-bottom: 14px;
    width: 100%;
}

.add-dialog-select {
    width: 100%;
    min-width: 0;
    box-sizing: border-box;
    border: 1.5px solid #e5e5e5;
    border-radius: 10px;
    padding: 12px 14px;
    font-size: 16px;
    background: #fafbfc;
    appearance: none;
    outline: none;
    transition: border 0.2s;
}

.add-dialog-select:focus {
    border: 1.5px solid #111;
    background: #fff;
}

.add-dialog-input {
    width: 100%;
    min-width: 0;
    box-sizing: border-box;
    border: 1.5px solid #e5e5e5;
    border-radius: 10px;
    padding: 12px 14px;
    font-size: 16px;
    background: #fafbfc;
    outline: none;
    transition: border 0.2s;
}

.add-dialog-input:focus {
    border: 1.5px solid #111;
    background: #fff;
}

.add-dialog-checkbox {
    display: flex;
    align-items: center;
    font-size: 15px;
    gap: 8px;
    color: #222;
    user-select: none;
}

.add-dialog-checkbox input[type='checkbox'] {
    width: 18px;
    height: 18px;
    accent-color: #111;
    border-radius: 4px;
}

.add-dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    margin-top: 6px;
}

.add-dialog-actions button {
    padding: 10px 28px;
    border: none;
    border-radius: 10px;
    font-size: 16px;
    background: #f2f2f2;
    color: #222;
    cursor: pointer;
    font-weight: 500;
    transition: background 0.2s, color 0.2s;
}

.add-dialog-actions button:last-child {
    background: #111;
    color: #fff;
    font-weight: 700;
}

:deep(.van-button--primary) {
    background-color: #111 !important;
    border-color: #111 !important;
}

:deep(.van-switch--on) {
    background: #111 !important;
    border-color: #111 !important;
}

.edit-btn {
    background: none;
    border: none;
    padding: 0 2px;
    cursor: pointer;
    display: flex;
    align-items: center;
    height: 36px;
    width: 36px;
    border-radius: 50%;
    transition: background 0.2s;
}

.edit-btn:active {
    background: #f2f2f2;
}

.edit-btn svg {
    display: block;
}

.copy-btn {
    background: none;
    border: none;
    padding: 0 2px;
    cursor: pointer;
    display: flex;
    align-items: center;
    height: 36px;
    width: 36px;
    border-radius: 50%;
    transition: background 0.2s;
}

.copy-btn:active {
    background: #f2f2f2;
}

.copy-btn svg {
    display: block;
}

/* 兼容性说明：-webkit-user-drag 仅支持 WebKit 浏览器，Firefox 不支持 */
</style>